package com.learning.security.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.learning.security.core.CustomSecurityMetadataSource;
import com.learning.security.core.filter.LoginKaptchaFilter;
import com.learning.security.core.handler.MyPersistentTokenBaseRememberMeService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.UrlAuthorizationConfigurer;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.security.SpringSessionBackedSessionRegistry;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

// @Configuration
// @EnableMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final UserDetailsService userDetailsService;

    private final DataSource dataSource;

    private final FindByIndexNameSessionRepository sessionRepository;

    private final CustomSecurityMetadataSource customSecurityMetadataSource;

    public SecurityConfig(UserDetailsService userDetailsService, DataSource dataSource, FindByIndexNameSessionRepository sessionRepository, CustomSecurityMetadataSource customSecurityMetadataSource) {
        this.userDetailsService = userDetailsService;
        this.dataSource = dataSource;
        this.sessionRepository = sessionRepository;
        this.customSecurityMetadataSource = customSecurityMetadataSource;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    // @Bean
    public LoginKaptchaFilter loginKaptchaFilter() throws Exception {
        LoginKaptchaFilter loginKaptchaFilter = new LoginKaptchaFilter();
        // 1.认证 url
        loginKaptchaFilter.setFilterProcessesUrl("/doLogin");
        // 2.认证 接收参数
        loginKaptchaFilter.setUsernameParameter("uname");
        loginKaptchaFilter.setPasswordParameter("passwd");
        loginKaptchaFilter.setKaptchaParameter("kaptcha");
        // 3.指定认证管理器
        loginKaptchaFilter.setAuthenticationManager(authenticationManagerBean());
        loginKaptchaFilter.setRememberMeServices(rememberMeServices());
        // 4.指定成功时处理
        loginKaptchaFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler());
        // 5.认证失败处理
        loginKaptchaFilter.setAuthenticationFailureHandler(authenticationFailureHandler());

        return loginKaptchaFilter;
    }

    private static AuthenticationFailureHandler authenticationFailureHandler() {
        return (request, response, exception) -> {
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("msg", "登录失败：" + exception.getMessage());
            result.put("code", 500);// 打印状态码   此处改为setStatus
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());// 设置登录失败之后的状态
            String s = new ObjectMapper().writeValueAsString(result);
            response.getWriter().println(s);
        };
    }

    private static AuthenticationSuccessHandler authenticationSuccessHandler() {
        return (request, response, authentication) -> {
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("msg", "登录成功");// 打印登录成功信息
            result.put("code", 200);// 打印状态码   此处改为setStatus
            result.put("data", authentication.getPrincipal());// 获得身份信息
            result.put("authentication", authentication);// 打印认证信息
            response.setContentType("application/json;charset=UTF-8");// 设置响应类型
            response.setStatus(HttpStatus.OK.value());// 设置登录成功之后的状态
            String s = new ObjectMapper().writeValueAsString(result);// json格式转字符串
            response.getWriter().println(s);// 打印json格式数据
        };
    }

    @Bean
    public RememberMeServices rememberMeServices() {
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        return new MyPersistentTokenBaseRememberMeService(UUID.randomUUID().toString(), userDetailsService(), jdbcTokenRepository);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        ApplicationContext applicationContext = http.getSharedObject(ApplicationContext.class);
        http.apply(new UrlAuthorizationConfigurer<>(applicationContext))
                .withObjectPostProcessor(objectPostProcessor());

        http.authorizeRequests()
                .mvcMatchers("/vc.jpg").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .cors()
                .configurationSource(configurationSource())
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint())
                .accessDeniedHandler(accessDeniedHandler())
                .and()
                .rememberMe()
                .rememberMeParameter("rememberme")
                .rememberMeServices(rememberMeServices())
                // .alwaysRemember(true) // 总是记住我
                .and()
                .logout()
                .logoutRequestMatcher(new OrRequestMatcher(
                        new AntPathRequestMatcher("/logout", HttpMethod.DELETE.name()),
                        new AntPathRequestMatcher("/logout", HttpMethod.GET.name())
                ))
                .logoutSuccessHandler(logoutSuccessHandler())
                .and()
                .csrf().disable()
                .sessionManagement()
                .maximumSessions(1)
                .expiredSessionStrategy(sessionInformationExpiredStrategy())
                .maxSessionsPreventsLogin(true)
                .sessionRegistry(sessionRegistry())
        ;

        /**
         * addFilterAt:用某个filter替换掉过滤器链中的某个filter
         * addFilterBefore():将某个过滤器放在过滤器链中某个filter之前
         * addFilterAfter():将某个过滤器放在过滤器链中某个filter之后
         */
        // http.addFilterAt(loginKaptchaFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    private ObjectPostProcessor<FilterSecurityInterceptor> objectPostProcessor() {
        return new ObjectPostProcessor<FilterSecurityInterceptor>() {
            @Override
            public <O extends FilterSecurityInterceptor> O postProcess(O object) {
                object.setSecurityMetadataSource(customSecurityMetadataSource);
                object.setRejectPublicInvocations(false);
                return object;
            }
        };
    }

    private static AccessDeniedHandler accessDeniedHandler() {
        return (request, response, e) -> { // 处理授权异常
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpStatus.FORBIDDEN.value());
            response.getWriter().write("无权访问!");
        };
    }

    CorsConfigurationSource configurationSource() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
        corsConfiguration.setAllowedMethods(Arrays.asList("*"));
        corsConfiguration.setAllowedOrigins(Arrays.asList("*"));
        corsConfiguration.setMaxAge(3600L);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);
        return source;
    }

    @Bean
    public SpringSessionBackedSessionRegistry sessionRegistry() {
        return new SpringSessionBackedSessionRegistry(sessionRepository);
    }

    private SessionInformationExpiredStrategy sessionInformationExpiredStrategy() {
        return event -> {// 匿名内部类优化
            HttpServletResponse response = event.getResponse();
            // map转json进行输出
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("msg", "当前会话已经失效,请重新登录!");
            String s = new ObjectMapper().writeValueAsString(result);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println(s);
            response.flushBuffer();
        };
    }

    // @Bean
    // public HttpSessionEventPublisher httpSessionEventPublisher() {
    //     return new HttpSessionEventPublisher();
    // }

    private static LogoutSuccessHandler logoutSuccessHandler() {
        return (request, response, authentication) -> {
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("msg", "注销成功");// 打印登录成功信息
            result.put("code", 200);// 打印状态码   此处改为setStatus
            result.put("data", authentication.getPrincipal());// 获得身份信息
            result.put("authentication", authentication);// 打印认证信息
            response.setContentType("application/json;charset=UTF-8");// 设置响应类型
            response.setStatus(HttpStatus.OK.value());// 设置登录成功之后的状态
            String s = new ObjectMapper().writeValueAsString(result);// json格式转字符串
            response.getWriter().println(s);// 打印json格式数据
        };
    }

    private static AuthenticationEntryPoint authenticationEntryPoint() {
        return (request, response, authException) -> {
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("msg", "请先登录");// 打印登录成功信息
            result.put("code", 200);// 打印状态码   此处改为setStatus
            response.setContentType("application/json;charset=UTF-8");// 设置响应类型
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            String s = new ObjectMapper().writeValueAsString(result);// json格式转字符串
            response.getWriter().println(s);// 打印json格式数据
        };
    }
}
